// pages/user/index.js
const http = require("../../api/http")
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    hasUserInfo: false,
    //是否可以调用获取信息得函数
    canIUseGetUserProfile: false,
    imgList: [],
    safeAreaTop: "",
    showCheckBox: false,
    deleteFileIds: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.getImages()
  },

  onPullDownRefresh() {
    this.getImages()
    wx.stopPullDownRefresh()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (app.globalData.reload) {
      this.getImages()
      app.globalData.reload = false
    }
  },
  /**
   * 上传图片
   */
  uploadImg: function () {
    const _this = this
    const imgList = this.data.imgList
    wx.chooseMedia({
      count: 9,
      mediaType: ['image'],
      sourceType: ['album'],
      success(res) {
        const tempFilePaths = res.tempFiles.map(filePath => ({
          src: filePath.tempFilePath,
          uploading: true,
          progress: 0,
          fileId: '',
          quote: 0
        }));
        const images = tempFilePaths.concat(imgList)
        _this.setData({
          imgList: images
        })
        // 上传图片
        setTimeout(() => {
          const tasks = []
          tempFilePaths.forEach((file, index) => {
            tasks.push(_this.uploadFile(file, index))
          })
          for (const index in tasks) {
            // 监听上传进度
            tasks[index].onProgressUpdate((res) => {
              const images = _this.data.imgList;
              images[index].progress = res.progress;
              _this.setData({
                imgList: images
              })
              _this.drawProgress(res.progress, index);
            });
          }
        }, 500)
      }
    })
  },
  uploadFile: function (file, index) {
    const _this = this
    return wx.uploadFile({
      url: `${app.globalData.server}/file/upload`, //仅为示例，非真实的接口地址
      filePath: file.src,
      name: 'file',
      header: {
        "Content-Type": "multipart/form-data",
        "cookie": wx.getStorageSync('cookies').toString()
      },
      formData: {
        type: 1
      },
      success(res) {
        const images = _this.data.imgList;
        images[index].uploading = false;
        images[index].fileId = res.data
        _this.setData({
          imgList: images
        });
      },
      fail: console.error,
    })
  },
  /**
 * 绘制进度圆环的方法。
 * @param {number} progress - 进度值，范围为0到100。
 * @param {number} index - 进度圆环的唯一标识索引。
 * 该方法通过wx.createSelectorQuery获取canvas节点，然后在其上绘制一个圆环，
 * 圆环的进度根据传入的progress参数决定。
 */
  drawProgress: function (progress, index) {
    const query = wx.createSelectorQuery()
    query.select(`#progressCanvas-${index}`)
      .fields({ node: true, size: true })
      .exec((res) => {
        if (res[0]) {
          const canvas = res[0].node
          canvas.width = 150
          canvas.height = 150
          const ctx = canvas.getContext('2d')
          const centerX = canvas.width / 2
          const centerY = canvas.height / 2
          const radius = 50
          const lineWidth = 5
          const startAngle = -0.5 * Math.PI
          const endAngle = (progress / 100) * 2 * Math.PI + startAngle
          // 清空画布
          ctx.clearRect(0, 0, canvas.width, canvas.height)
          // 绘制背景圆环
          ctx.beginPath()
          ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false)
          ctx.lineWidth = lineWidth
          ctx.strokeStyle = '#e6e6e6'
          ctx.stroke()

          // 绘制进度条
          ctx.beginPath()
          const gradient = ctx.createLinearGradient(
            centerX - radius,
            centerY,
            centerX + radius,
            centerY,
          )
          gradient.addColorStop(0, '#56B37F')
          gradient.addColorStop(1, '#c0e674')
          ctx.arc(centerX, centerY, radius, startAngle, endAngle, false)
          ctx.lineWidth = lineWidth
          ctx.strokeStyle = gradient
          ctx.stroke()
          // 绘制进度文本
          ctx.font = '20px Arial'
          ctx.fillStyle = '#fff'
          ctx.textAlign = 'center'
          ctx.textBaseline = 'middle'
          ctx.fillText(`${progress}%`, centerX, centerY)
        }
      })
  },
  /**
   * 获取用户的图库
   */
  getImages() {
    const _this = this
    http.post("/file/getPage", {
      pageNum: 1,
      pageSize: 100
    }).then((res) => {
      const records = res.data.records || []
      const images = []
      for (const file of records) {
        if (file.fileId) {
          images.push({ "src": `${app.globalData.server}/file/downLoad?fileId=${file.fileId}&type=1`, "fileId": file.fileId, quote: file.quote })
        }
      }
      _this.setData({
        imgList: images,
        showCheckBox: false,
      })
    })
  },
  longtabHandle: function (event) {
    const { fileId, quote } = event.currentTarget.dataset
    const imgList = this.data.imgList
    if (quote === 0) {
      for (const img of imgList) {
        if (fileId === img.fileId) {
          img.checked = true
          break
        }
      }
    }
    this.setData({
      imgList: imgList,
      showCheckBox: true
    })
  },

  /**
   * 删除
   */
  deleteHandle: function () {
    const fileIds = this.data.deleteFileIds
    let imgList = this.data.imgList
    const _this = this
    if (!fileIds || fileIds.length === 0) {
      wx.showToast({
        title: '请先选择要删除的图片',
        icon: "error"
      })
      return
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '删除将无法恢复，请确认是否删除',
        complete: (res) => {
          if (res.confirm) {
            http.post("/file/batchDelete", fileIds).then((res) => {
              imgList = imgList.filter(item => !fileIds.includes(item.fileId))
              _this.setData({
                showCheckBox: false,
                imgList: imgList
              })
            })
          }
        }
      })
    }
  },
  checkboxChangeTip(event) {
    const { id, quote } = event.currentTarget.dataset
    const imgList = this.data.imgList
    const files = imgList.filter(item => item.fileId === id)
    const _this = this
    if (files[0] && files[0].checked) {
      _this.checkboxChange(id)
    } else {
      if (quote !== 0) {
        wx.showModal({
          title: '提示',
          content: '此图已经排版，删除会导致排好的丢失图片，如要删除请先删除排好的模板？',
          complete: (res) => {
            if (res.confirm) {
            }
          }
        })
      } else {
        _this.checkboxChange(id)
      }
    }
  },
  /**
   * 选中
   * @param {*} event 
   */
  checkboxChange(id) {
    let deleteFileIds = this.data.deleteFileIds
    if (!deleteFileIds.includes(id)) {
      deleteFileIds.push(id)
    } else {
      deleteFileIds = deleteFileIds.filter(fileId => fileId !== id)
    }
    let images = this.data.imgList
    for (const image of images) {
      if (image.fileId === id) {
        image.checked = !image.checked
      }
    }
    this.setData({
      deleteFileIds: deleteFileIds,
      imgList: images
    })
  },
  imgClickTip(event) {
    const imgList = this.data.imgList
    const { fileId, quote } = event.currentTarget.dataset
    const files = imgList.filter(item => item.fileId === fileId)
    const _this = this
    if (!this.data.showCheckBox) {
      const urls = imgList.map(item => item.src)
      wx.previewImage({
        current: files[0].src, // 当前显示图片的http链接
        urls: urls// 需要预览的图片http链接列表
      })
      return
    }
    if (files[0] && files[0].checked) {
      _this.imgClickHandle(event)
    } else {
      if (quote !== 0) {
        wx.showModal({
          title: '提示',
          content: '此图已经排版，删除会导致排好的丢失图片，如要删除请先删除排好的模板？',
          complete: (res) => {
            if (res.confirm) {
            }
          }
        })
      } else {
        _this.imgClickHandle(event)
      }
    }
  },
  /**
   * 图片点击事件
   * @param {Object} event 
   */
  imgClickHandle(event) {
    if (this.data.showCheckBox) {
      const { fileId } = event.currentTarget.dataset
      const imgList = this.data.imgList
      let deleteFileIds = this.data.deleteFileIds
      for (const img of imgList) {
        if (fileId === img.fileId) {
          img.checked = !img.checked
          if (img.checked) {
            if (!deleteFileIds.includes(fileId)) {
              deleteFileIds.push(fileId)
            }
          } else {
            deleteFileIds = deleteFileIds.filter(id => id !== fileId)
          }
          break
        }
      }
      this.setData({
        imgList,
        deleteFileIds
      })
    }
  },
  /**
   * 选择
   * @param {*} e 
   */
  selecteHandle(e) {
    let imgList = this.data.imgList
    if (this.data.showCheckBox) {
      imgList.map(item => item.checked = false)
    }
    this.setData({
      imgList,
      deleteFileIds: [],
      showCheckBox: !this.data.showCheckBox
    })
  }
})